/////////////////////////////////////////////
/// Implementation of the who needs a xoperator
/////////////////////////////////////////////


query = "PREFIX foaf: <http://xmlns.com/foaf/0.1/> PREFIX xop: <http://ns.aksw.org/xop/> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>"+ 
		"SELECT ?name ?firstname ?lastname ?s ?label "+ 
		"WHERE { ?s a foaf:Agent. OPTIONAL {?s xop:xoperator ?z} . "+ 
		"OPTIONAL {?s foaf:name ?name}. OPTIONAL {?s foaf:surname ?lastname}. OPTIONAL {?s foaf:firstName ?firstname}. OPTIONAL {?s rdfs:label ?label} " +
		" FILTER (!bound(?z))}"
context.log.info(query);
found = false;
error ="";
agents = [:]	
context.queryForTable(query,true,[],null).each{res->
	if(res.errors==null||res.errors.empty){
			res.resultRows.each{row->
				user = ""
				if(row["name"]!=null){
					user = row["name"]
				}else{
					if(row["firstname"] !=null){ 
						user = row["firstname"]
					} 
					if(row["lastname"] !=null){
					user += row["lastname"]
					}
				}
				if(user.empty && row["label"]!=null){
					user = row["label"]
				}
				if(user.empty){
					user = row["s"];
				}
				if(agents[row["s"]]==null){
					agents[row["s"]] = user + " (by: " + res.storeName;
				}else{
					agents[row["s"]] += ", " +  res.storeName;
				}
				
				found = true;
				}

	}else{
		error += " " + res.storeName +": " + res.errors
	}
	
}

agents.each{key,value ->
	context.sendMessageToUser(  value +  ")");
}


if(!found){
		context.sendMessageToUser("Nobody");
}

if(!error.empty){
	context.sendMessageToUser("Some error occured: " + error);
}
